package com.qq.spirit;

import java.util.Iterator;
import java.util.List;

import org.apache.http.Header;

import com.qq.spirit.inter.AbstractXmlActionAfterRequest;
import com.qq.spirit.inter.TaskUnit;
import com.qq.spirit.model.UserData;
import com.qq.spirit.model.XmlDataUtil;
import com.qq.spirit.model.XmlNodeData;

public class SessionHolderTask implements Runnable
{

	@Override
	public void run()
	{
		try
		{

			Iterator<Integer> ite = GameUserInfoUtil.userIte();
			while (ite.hasNext())
			{
				Integer gid = ite.next();
				TaskManager.addTask(new SessionHolder(gid));
			}
		} catch (Exception ex)
		{
			LoggerUtil.error(0, ex);
		}
	}

	class SessionHolder extends TaskUnit
	{

		public SessionHolder(int gid)
		{
			super();
			this.gid = gid;
		}

		@Override
		public void doTask()
		{
			UserData u = GameUserInfoUtil.getUser(gid);
			if (u.getUserState() == UserState.LOGIN_GAME)
			{
				HttpUtil.doGet(gid, GameConstants.PLAY_USER_INFO_URL, new SessionHolderResult(gid));
			} else
			{
				// 添加登录任务先
				TaskManager.addTask(new LoginTask(gid, this));
			}
		}
	}

}

/**
 * 会话保持
 * 
 * @author beedoorwei
 * 
 */
class SessionHolderResult extends AbstractXmlActionAfterRequest
{
	public SessionHolderResult(int gid)
	{
		super();
		this.gid = gid;
	}

	@Override
	public void doCall(List<Header> headerList, XmlNodeData resultData)
	{
		UserData u = GameUserInfoUtil.getUser(gid);
		u.setUserState(UserState.LOGIN_GAME);
		u.setGameInfo("game_nickname", XmlDataUtil.getNodeData(resultData, "results.player.playername"));
	}
}
